package com.example.demo.all.sse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zwg
 * @date 2025/2/27 16:47
 */
@Slf4j
public class SseEmitterCache {
    private static final String DEFAULT_SSE_ID = "SSE_ID_0001";
    protected static final Map<String, SseEmitter> emitterMap = new ConcurrentHashMap<>();

    public static synchronized SseEmitter getSseEmitter(String sseId) {
        final String _sseId = org.springframework.util.StringUtils.hasText(sseId) ? sseId : DEFAULT_SSE_ID;
        SseEmitter sse = emitterMap.getOrDefault(_sseId, null);
        if (sse == null) {
            sse = new SseEmitter(60000L); //ms
            sse.onCompletion(new CleanSseEmitterThread(_sseId));
            sse.onTimeout(new CleanSseEmitterThread(_sseId));
            emitterMap.put(_sseId,sse);
            log.info("add sseEmitter : {}  map.size:{}", _sseId, emitterMap.size());
        }

        return sse;
    }
}
